<template>
  <div class="waterfall">
    <div v-for="(item, index) in columnData" :key="index"
         class="flex flex-col items-center" :style="{ width: `${columnWidth}px` }">
      <template v-for="childItem in item">
        <div :id="`item${childItem.id}`" @click.stop="click(childItem)">
          <slot :item="childItem">
            <div class="item" style="background-color:#fff;margin:10rpx;border-radius:8rpx;">
              <image :src="childItem.imgUrl" mode="widthFix" lazy-load
                     :style="{ height: childItem.height, width: '100%' }" />
              <div class="title-info">
                <div class="item-title">{{ childItem.title }}</div>
                <div class="item-desc">{{ childItem.desc }}</div>
              </div>
            </div>
          </slot>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">

const props = defineProps({
  datalist: { type: Array, required: true, default: () => [] },
  // basedata: { type: Array, required: false, default: () => [] },
  //显示列数
  column: { type: Number, required: true, default: 2 },
  resetwidth: { type: Number },
})
const emit = defineEmits(['click'])

let columnData: any = $ref([])
let columnWidth = $ref(0)

watch(() => props.resetwidth, () => {
  setColumnWidth()
})

watch(() => props.datalist.length, () => {
  nextTick(() => {
    if (props.datalist.length > 0) {
      setColumnWidth()
      setData()
    }
  })
}, { immediate: true, deep: true })

// watch(() => props.basedata, () => {
//   nextTick(() => {
//     setColumnWidth()
//     setData()

//   })
// }, { immediate: true, deep: true })

// watch(() => props.column, () => {
//   nextTick(() => {
//     setColumnWidth()
//     setData()
//   })
// }, { immediate: true, deep: true })

const instance = getCurrentInstance()
//计算每列的高度
const getElemHeight = () => {
  nextTick(() => {
    let arr: any = []
    props.datalist.forEach((item: any) => {
      uni.getImageInfo({
        src: item.imgUrl,
        success: (e) => {
          item.height = `${e.height * (columnWidth / e.width)}px`
          uni.createSelectorQuery().in(instance)
            .select(`#item${item.id}`)
            .boundingClientRect((res: any) => {
              arr.push({
                itemHeight: `${e.height * (columnWidth / e.width)}`,
                ...item,
              })
              if (arr.length === props.datalist.length) {
                columnData = distributeToNArrays(arr, props.column)
              }
              console.log(arr)
            }).exec()
        },
      })
    })
  })
}
const distributeToNArrays = (arr, n) => {
  let sums = new Array(n).fill(0)

  return arr.reduce(
    (arrays, item) => {
      let minSum = Math.min(...sums)
      let minIndex = sums.indexOf(minSum)
      arrays[minIndex].push(item)
      console.log(arrays)

      sums[minIndex] += Number(item.itemHeight)
      return arrays
    },
    new Array(n).fill(0).map(() => []),
  )

}


const setColumnWidth = () => {
  const width = uni.getSystemInfoSync().windowWidth
  columnWidth = Math.floor(width / props.column)
}
const setData = () => {
  const resultArray = props.datalist.reduce(
    (acc: any, cur, index) => {
      const targetIndex = index % props.column
      acc[targetIndex].push(cur)
      return acc
    },
    Array.from(Array(props.column), () => []),
  )
  columnData = resultArray
}
const click = (item) => {
  emit('click', item)
}
</script>

<style lang="scss" scoped>
.waterfall {
  display: flex;

  .item {
    overflow: hidden;
  }

  .title-info {
    padding: 0rpx 20rpx 20rpx;
  }

  .item-title {
    font-size: 30rpx;
    color: #333;
    line-height: 46rpx;
    text-align: justify;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 1;
  }

  .item-desc {
    margin-top: 4rpx;
    font-size: 26rpx;
    color: #666;
    line-height: 34rpx;
    text-align: justify;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
}
</style>
